package filejoiner.util;

import java.io.*;

/**
 *
 * @author Luis
 */
public class FileUtils {

    private Integer fileSize;
    private Integer outSize;
    private FileInputStream fileInputStream;
    private BufferedInputStream bufferedInputStream;

    public FileUtils(File file, Integer outSize) throws FileNotFoundException {
        this.outSize = outSize;
        fileSize = (int) file.length();
        fileInputStream = new FileInputStream(file);
        bufferedInputStream = new BufferedInputStream(fileInputStream);
    }

    public byte[] split() throws IOException {
        byte[] bs = bufferedInputStream.available() < outSize ? new byte[bufferedInputStream.available()] : new byte[outSize];
        bufferedInputStream.read(bs);
        return bs;
    }

    private byte[] split(Integer maskSize) throws IOException {
        byte[] bs = bufferedInputStream.available() < (outSize - maskSize) ? new byte[bufferedInputStream.available()] : new byte[(outSize - maskSize)];
        bufferedInputStream.read(bs);
        return bs;
    }

    public byte[] mask(File fileMask) throws IOException {
        byte[] fileBytes = split((int) fileMask.length());
        byte[] fileMaskBytes = getBytes(fileMask);
        return concat(fileMaskBytes, fileBytes);
    }

    public byte[] concat(byte[] mask, byte[] file) {
        byte[] bs = new byte[mask.length + file.length];
        System.arraycopy(mask, 0, bs, 0, mask.length);
        System.arraycopy(file, 0, bs, mask.length, file.length);
        return bs;
    }

    public Boolean hasNext() throws IOException {
        return bufferedInputStream.available() > 0 ? true : false;
    }

    public Integer getFileSize() {
        return fileSize;
    }

    public Integer getOutSize() {
        return outSize;
    }

    public static byte[] getBytes(File file) throws IOException {
        byte[] bs;
        InputStream is = new FileInputStream(file);
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
        bs = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bs.length
                && (numRead = is.read(bs, offset, bs.length - offset)) >= 0) {
            offset += numRead;
        }
        if (offset < bs.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        is.close();
        return bs;
    }

    public void write(byte[] bs, String path, String fileName) throws IOException {
        OutputStream out = new FileOutputStream(path + "/" + fileName);
        out.write(bs);
    }
}
